<template>
  <div class="page-Body">
    <div v-if="!$route.params.id">
      <h2 class="page-title">角色管理</h2>
      <!-- 表单 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input
            v-model="formInline.roleName"
            placeholder="请输入用户名称"
            clearable
            style="width: 150px"
            v-noSpace
          />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input
            v-model="formInline.roleCode"
            placeholder="请输入权限字符"
            clearable
            style="width: 150px"
            v-noSpace
          />
        </el-form-item>
        <el-form-item label="角色状态">
          <el-select
            v-model="formInline.banned"
            placeholder="请输入用户状态"
            clearable
            style="width: 150px"
          >
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <TimeFormatter
            @TimeChild="TimeHandle"
            ref="childComponentRef"
          ></TimeFormatter>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="Search">搜索</el-button>
          <el-button @click="Reset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 新增对话框组件 -->
      <el-button
        plain
        @click="AddOpenDialog"
        class="el-DiaButton"
        type="primary"
      >
        添加
      </el-button>
      <AddRole_Dialog
        @confirm="AddConfirm"
        @cancel="AddClose"
        :dialogAdd="dialogAdd"
      />
      <!-- 可滚动的内容区域 -->
      <div class="page-content">
        <!-- 表格 -->
        <el-table
          ref="myTableRef"
          :data="tableData"
          border
          stripe
          fit
          empty-text="暂无数据"
          show-header
          v-loading="loading"
          size="default"
          element-loading-text="Loading..."
          :header-cell-style="{ background: '#e7e1fb' }"
          style="width: 100%"
          max-height="550px"
        >
          <el-table-column prop="id" label="序号" />
          <el-table-column prop="roleName" label="角色名称" />
          <el-table-column prop="roleCode" label="权限字符" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="banned" label="状态" v-slot="scope">
            <span :style="scope.row.banned === 0 ? {} : { color: 'red' }">
              {{ scope.row.banned === 0 ? '启用' : '禁用' }}
            </span>
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            v-slot="scope"
          >
            <el-button
              link
              type="primary"
              @click="ModifyOpenDialog(scope.row.id)"
            >
              修改
            </el-button>
            <el-button
              link
              type="primary"
              @click="AssigningUsers(scope.row.id)"
            >
              分配用户
            </el-button>
            <el-button link type="danger" @click="Del(scope.row.id)">
              删除
            </el-button>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 40, 80, 100]"
          background
          layout="total,sizes, prev, pager, next,jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 修改对话框组件 -->
      <ModifyRole_Dialog
        @confirm="ModifyConfirm"
        @cancel="ModifyClose"
        :dialogModify="dialogModify"
        :NewModifyList="NewModifyList"
      />
    </div>
    <div v-else>
      <router-view></router-view>
    </div>
  </div>
</template>

<script setup name="RoleManagementPage">
import { getRoleList, DelRoleList } from '@/api/permission/role';
import { ref, onMounted } from 'vue';
import AddRole_Dialog from '@/components/permission/AddRole_Dialog.vue';
import ModifyRole_Dialog from '@/components/permission/ModifyRole_Dialog.vue';
import TimeFormatter from '@/components/permission/TimeFormatter.vue';
import { useRouter } from 'vue-router';

const router = useRouter();
// 分页变量
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 对话框
const dialogAdd = ref(false);
const dialogModify = ref(false);
const NewModifyList = ref([]);
// 表单-时间选择器
const childComponentRef = ref(null);
const TimeArray = ref([]);
// 表单数据
const formInline = ref({
  roleName: '',
  roleCode: '',
  banned: '',
});
// 列表数据+表单校验
const tableData = ref([]);
const loading = ref(true);
const myTableRef = ref(null);
// 分页逻辑
const handleSizeChange = async (val) => {
  pageSize.value = val;
  RoleList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  RoleList();
};
// 获取列表
const RoleList = async () => {
  loading.value = true;
  const res = await getRoleList({
    current: currentPage.value,
    size: pageSize.value,
    query: {},
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data.items;
    total.value = res.data.data.counts || 0;
    loading.value = false;
  }
};
// 检查搜索条件是否为空
const hasSearchConditions = () => {
  const { roleName, roleCode, banned } = formInline.value;
  return roleName || roleCode || banned;
};
// 搜索
const Search = async () => {
  if (!hasSearchConditions()) {
    // eslint-disable-next-line no-undef
    ElMessage({
      message: '请至少输入一个搜索条件',
      type: 'warning',
    });
    return;
  }
  loading.value = true;
  const res = await getRoleList({
    current: currentPage.value,
    size: pageSize.value,
    query: { ...formInline.value },
    startDate: TimeArray.value[0],
    endDate: TimeArray.value[1],
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data.items;
    total.value = res.data.data.counts || 0;
    loading.value = false;
  }
};
// 重置
const Reset = () => {
  // 如果当前已经是空值状态，直接返回
  if (
    TimeArray.value.length === 0 &&
    formInline.value.roleName === '' &&
    formInline.value.roleCode === '' &&
    formInline.value.banned === ''
  ) {
    return;
  }
  formInline.value = {};
  if (childComponentRef.value) {
    childComponentRef.value.clear();
  }
  RoleList();
};

// 删除
const Del = async (id) => {
  // eslint-disable-next-line no-undef
  ElMessageBox.confirm('确定删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await DelRoleList(id);
      if (res.data.code === 3000) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '无权限操作',
          type: 'warning',
        });
      } else if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '删除成功',
          type: 'success',
        });
        RoleList();
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'warning',
        });
      }
    })
    .catch(() => {});
};

// 添加功能对话框
const AddOpenDialog = () => {
  dialogAdd.value = true;
};

const AddConfirm = () => {
  RoleList();
};
const AddClose = () => {
  dialogAdd.value = false;
};

// 修改功能对话框
const ModifyOpenDialog = (Roleid) => {
  NewModifyList.value = tableData.value.filter((item) => {
    return item.id == Roleid;
  });
  dialogModify.value = true;
};

const ModifyConfirm = () => {
  RoleList();
};
const ModifyClose = () => {
  dialogModify.value = false;
};

// 分配用户
const AssigningUsers = (id) => {
  router.push({
    name: 'assignUsers',
    params: { id },
  });
};
//获取时间
const TimeHandle = (data) => {
  TimeArray.value = data;
};
onMounted(() => {
  RoleList();
});
</script>

<style lang="scss" scoped>
.el-table {
  flex: 1;
}
</style>
